<?php

namespace App\Supports\Payment\Methods\Alipay;

use Exception;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodPay;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Redis;
use App\Models\User;
use Rainsens\Dinglog\Facades\Dinglog;

class PayStorm extends Method implements MethodPay
{
	public function validate($orderIds = [])
	{

		if(!$orderIds){
			fail('请求订单不存在');
		}
		
		$orderList = [];
		$money = big_decimal(0);
		
		foreach($orderIds as $value){
			$order = Redis::hGetAll($value);

			if(empty($order)){

				fail('目标订单不存在');
			}

			if ($order['is_paid'] == true) {
				fail('目标订单已支付');
			}
			if(isset($order['is_paying'])){
				if ($order['is_paying'] == true) {
					fail('目标订单正在支付');
				}
			}
			

			$orderList[] = $order;
			
		}

		$userId = array_column($orderList,"user_id")[0];
		$user = User::find($userId);
		$this->user = $user;


		return $orderList;
		/*if ($order->isPaid()) {
			fail('目标订单已支付');
		}
		if ($order->isClosed()) {
			fail('目标订单已关闭');
		}*/
	}
	
	public function info($data=[]) {

		$outTradeNo = 'record_'.$data['mergeNumber'];
		$subject = '掌上金店订单: ' . $data['mergeNumber'];
		$totalAmount = $data['amount'];
		
		return [
			'out_trade_no' => $outTradeNo,
			'total_amount' => $totalAmount,
			'subject' => $subject,
		];

	}
	
	public function pay($orderIds=[])
	{

		$orderList = $this->validate($orderIds);

		$amountArr = array_column($orderList,'record_all_price');
		$mergeNumber = $orderList[0]['cid']."_".rand(1000,9999);
		$amount = array_sum($amountArr);

		$data = ['mergeNumber' => $mergeNumber,'amount'=>$amount];

		foreach($orderList  as $k=>$value){
			//$this->user->markRecordPayCachePaying($value['cid']);
			Redis::hMset($value['cid'],['merge_number'=>$mergeNumber]);
			Redis::zAdd($mergeNumber , 1, $value['cid']);
		}
		Dinglog::text(json_encode($data));
		$info = $this->info($data);
		Dinglog::text(json_encode($info));
		return $this->channel->pay($info);
	}
}
